<template>
  <div class="main">
    <div class="cont">
      <searchBar @search="searchCart($event)"></searchBar>
      <div class="commodity">
        <div class="top">
          <p v-if="tableData.data">
            {{ t("全部商品") }} ({{ tableData.data.length }})
          </p>
          <div class="address">
            <p>{{ t("配送至") }}:</p>
            <div class="address-div" @click="addressClick()">
              <span>{{
                currentAddress
                  ? currentAddress.country +
                    currentAddress.province +
                    currentAddress.city +
                    currentAddress.district
                  : ""
              }}</span>
              <img src="../../assets/images/home/right.png" alt="" />
            </div>
          </div>
        </div>
        <div class="details" v-loading="cart_loading">
          <el-table
            ref="multipleTable"
            :data="tableData.data"
            :key="tableData.id"
            tooltip-effect="dark"
            style="width: 100%"
            :row-class-name="tableRowClassName"
            :header-cell-style="{
              background: '#F1F1F1',
              color: '#000000',
              height: '50px',
            }"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="150"></el-table-column>
            <el-table-column :label="t('商品')" width="400">
              <template slot-scope="scope">
                <div style="display: flex">
                  <img
                    v-if="scope.row.sku.images"
                    :src="scope.row.sku.images.split(',')[0] | imgSrc"
                    alt=""
                    style="
                      border: 1px solid #e3e3e3;
                      border-radius: 5px;
                      object-fit: contain;
                      width: 60px;
                      height: 60px;
                      margin-right: 10px;
                    "
                  />
                  <div>
                    <p class="ptb10">{{ scope.row.goods.title }}</p>
                    <p v-if="scope.row.sku">
                      {{ t("颜色") }}：{{ scope.row.sku.difference }}
                    </p>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="t('单价')" width="250">
              <template slot-scope="scope" v-if="scope.row.goods">
                <p>￥{{ scope.row.sku.price }}</p>
              </template>
            </el-table-column>
            <el-table-column :label="t('数量')" width="250">
              <template v-if="scope.row.number > 0" slot-scope="scope">
                <div style="display: flex; align-items: center">
                  <img
                    src="../../assets/images/home/jian.png"
                    alt=""
                    @click="goodsNum(scope.row, 'sub')"
                  />
                  <span class="font18 fwbold" style="margin: 0px 10px">{{
                    scope.row.number
                  }}</span>
                  <img
                    src="../../assets/images/home/jia.png"
                    alt=""
                    @click="goodsNum(scope.row, 'add')"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="t('小计')" width="300">
              <template slot-scope="scope" v-if="scope.row.number > 0">
                <p>
                  ￥{{ (scope.row.goods.price * scope.row.number).toFixed(2) }}
                </p>
              </template>
            </el-table-column>
            <el-table-column :label="t('操作')" width="300">
              <template slot-scope="scope">
                <button
                  style="
                    width: 80px;
                    height: 40px;
                    background: #ff0000;
                    border-radius: 10px;
                    border: 0;
                    color: #fff;
                  "
                  @click="delItems(scope.row, 'signle')"
                >
                  {{ $t("删除") }}
                </button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="page">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="tableData.total"
          :hide-on-single-page="true"
        >
        </el-pagination>
      </div>
    </div>
    <div class="footer-p"></div>
    <div class="footer">
      <div class="left">
        <p @click="delItems(undefined, 'select')">{{ t("删除选中的商品") }}</p>
        <p @click="delItems(undefined, 'all')">{{ t("清理购物车") }}</p>
      </div>
      <div class="right">
        <p>{{ t("商品总计", { num: settlement.number }) }}</p>
        <p>
          {{ t("总价") }}:
          <span class="price">￥{{ settlement.totalPrice }}</span>
        </p>
        <p class="discounts" @click="show_coupon_dialog()">
          {{ t("共减") }}￥<span>{{ settlement.cutPrice }}</span>
        </p>
        <button class="pay" @click="gopay">{{ t("去结算") }}</button>
      </div>
    </div>
    <div class="addpop">
      <el-dialog
        :title="t('选择地址')"
        :visible.sync="addressDialog.show"
        width="70%"
      >
        <template v-if="addressDialog.action == 'select'">
          <addressSelect @select="addressSelect($event)"></addressSelect>
        </template>
        <template v-if="addressDialog.action == 'add'">
          <addressEidt @editAddress="addAddress($event)"></addressEidt>
        </template>
      </el-dialog>
    </div>
    <div class="dctpop">
      <el-dialog
        :title="t('优惠明细')"
        :visible.sync="dialogVisible"
        width="30%"
        center
      >
        <p>{{ settlement.couponText }}</p>
        <span slot="footer" class="dialog-footer">
          <el-button style="color: #fff" @click="to_coupon_list()">{{
            t("去使用其他优惠")
          }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// const cityOptions = ['上海', '北京', '广州', '深圳'];
import searchBar from "@/components/searchBar.vue";
import addressEidt from "@/components/addressEidt.vue";
import addressSelect from "@/components/addressSelect.vue";
import {
  shopcartList,
  updateShopCartNum,
  deleteShopCartGoods,
  orderCreate,
  addressDetail,
  addressAdd,
  getCouponPrice,
} from "@/utils/api";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    searchBar,
    addressEidt,
    addressSelect,
  },
  data() {
    //这里存放数据
    return {
      searchText: "",
      tableData: {},
      multipleTable: [],
      /**
       * 结算底部视图
       */
      settlement: {
        can_use: true,
        number: 0, //数量
        totalPrice: 0, //总价
        cutPrice: 0, //优惠价
        couponText: "", //优惠券名字
      },
      addressDialog: {
        show: false,
        action: null,
      },
      currentAddress: null,
      dialogVisible: false,
      cart_loading: false, // 网络加载
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    /**
     * 简化翻译方法(少写property)
     * @param {String} v 最后一个key值
     */
    t(v, opt) {
      if (opt) {
        return this.$t(`购物车.${v}`, opt);
      }
      return this.$t(`购物车.${v}`);
    },
    /**
     * 获取购物车列表数据
     */
    getList() {
      this.cart_loading = true;
      shopcartList({
        title: this.searchText,
      }).then((res) => {
        this.cart_loading = false;
        if (res.code == 1) {
          this.tableData = res.data;
          if (this.$route.params.ids) {
            let idArr = this.$route.params.ids.split(",");
            this.$nextTick(() => {
              this.settlement.can_use = false;
              this.tableData.data.forEach((el) => {
                if (idArr.includes(`${el.id}`)) {
                  this.$refs.multipleTable.toggleRowSelection(el, true);
                  this.multipleTable.push(el);
                }
              });
              this.settlement.can_use = true;
              this.handleSelectionChange(this.multipleTable);
            });
          }
        }
      });
    },
    /**
     * 计算底部视图的价格
     */
    handleSelectionChange(val) {
      if (!this.settlement.can_use || val.length < 1) return;
      this.multipleTable = val;
      let ids = val.map((e) => e.id).join(",");
      this.cart_loading = true;
      getCouponPrice({ cart_ids: ids }).then((res) => {
        this.cart_loading = false;
        if (res.code == 1) {
          this.settlement.totalPrice = res.data.pay_price;
          this.settlement.cutPrice = res.data.coupon_price;
          this.settlement.number = res.data.goods_num;
          this.settlement.couponText = res.data.coupon_text;
        }
      });
    },
    tableRowClassName(row) {
      // console.log(row.row);
      if (row.row.valid == 0) {
        return "elactive";
      }
    },
    /**
     * @param {Object} item 当前选中商品
     * @param {string} [type='add', type='sub'] 加,减
     */
    async goodsNum(item, type = "add") {
      if (item.number <= 1 && type == "sub") {
        this.$message({
          message: this.t("数量不能小于1"),
          type: "error",
        });
        return;
      }
      this.cart_loading = true;
      let res = await updateShopCartNum({
        cart_id: item.id,
        style: type == "add" ? "1" : "2",
      });
      this.cart_loading = false;
      if (res.code != 1) {
        return;
      }
      if (type == "add") {
        item.number++;
      } else if (type == "sub") {
        item.number--;
      }
      if (this.multipleTable.includes(item)) {
        this.handleSelectionChange(this.multipleTable);
      }
    },
    /**
     * 删除项目
     */
    delItems(item, type = "signle") {
      let cart_ids = "";
      if (type == "signle") {
        cart_ids = item.id;
      } else if (type == "select") {
        cart_ids = this.multipleTable.map((e) => e.id).join(",");
      } else if (type == "all") {
        cart_ids = this.tableData.data.map((e) => e.id).join(",");
      }
      if (cart_ids == "") {
        this.$message.error(this.t("请选择要删除的商品"));
        return;
      }
      this.cart_loading = true;
      deleteShopCartGoods({ cart_id: cart_ids }).then((res) => {
        this.cart_loading = false;
        if (res.code == 1) {
          this.getList();
          this.handleSelectionChange(this.multipleTable);
        }
      });
    },
    addressClick() {
      // this.$router.push({ path: "/accountInfo/address", query: { aside: 1 } });
      this.addressDialog = {
        show: true,
        action: "select",
      };
    },
    editAddressHandle(e) {
      this.currentAddress = e;
      this.addressDialog = {
        show: false,
        action: null,
      };
    },
    gopay() {
      // this.$router.push("closing")
      if (!this.multipleTable.length) {
        this.$message.error(this.t("请选择商品"));
        return;
      }
      if (!this.currentAddress) {
        this.addressDialog = {
          show: true,
          action: "add",
        };
        return;
      }
      let goods = this.multipleTable.map((e) => {
        return { sku_id: e.sku_id, number: e.number, goods_id: e.goods_id };
      });
      this.cart_loading = true;
      orderCreate({
        goods: goods,
        address_id: this.currentAddress.id,
        coupon_id: "",
      }).then((res) => {
        this.cart_loading = false;
        if (res.code == 1) {
          this.$router.push({ path: "order", query: { type: 0 } });
        }
      });
    },
    addressSelect(e) {
      this.currentAddress = e;
      this.addressDialog = { show: false };
    },
    addAddress(e) {
      this.cart_loading = true;
      addressAdd({
        ...e,
      }).then((res) => {
        this.cart_loading = false;
        if (res.code == 1) {
          this.$message.success(res.msg);
          this.addressDialog.show = false;
          this.currentAddress = { ...e, id: res.data };
        }
      });
    },
    show_coupon_dialog() {
      if (this.multipleTable.length < 1) {
        this.$message.error(this.t("请选择商品"));
        return;
      }
      this.dialogVisible = true;
    },
    /**
     * 跳转优惠券
     */
    to_coupon_list() {
      if (this.multipleTable.length < 1) {
        this.$message.error(this.t("请选择商品"));
        return;
      }
      this.$router.push({
        name: "coupon",
        query: {
          activeName: "0",
          ids: this.multipleTable.map((e) => e.id).join(","),
        },
      });
    },
    searchCart(e) {
      this.searchText = e;
      this.getList();
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getList();
    addressDetail({ id: 0 }).then((res) => {
      if (res.code == 1) {
        this.currentAddress = res.data;
      }
    });
  },
};
</script>
<style lang="less" scoped>
.main {
  min-height: calc(100vh - 90px);
  background-color: #f9f9f9;

  .cont {
    margin: 0px 105px;
    display: flex;
    justify-content: center;
    flex-flow: row wrap;

    .commodity {
      width: 100%;
      display: flex;
      justify-content: flex-start;
      flex-direction: column;
      background: #ffffff;

      .top {
        height: 80px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 20px;

        p {
          font-size: 20px;
          font-weight: bold;
          color: #000000;
        }

        .address {
          display: flex;
          align-items: center;

          p {
            font-size: 16px;
            font-weight: 400;
            color: #000000;
            margin-right: 10px;
          }

          .address-div {
            box-sizing: border-box;
            width: 200px;
            height: 45px;
            padding: 14px 12px;
            background: #f9f9f9;
            border-radius: 5px;

            display: flex;
            align-items: center;
            justify-content: space-around;
            cursor: pointer;

            span {
              font-size: 16px;
              font-weight: 400;
              color: #666666;
            }

            img {
              width: 20px;
              height: 20px;
            }
          }
        }
      }

      .details {
        width: 100%;
        display: flex;
        flex: 1;
      }
    }

    .page {
      width: 100%;
      display: flex;
      justify-content: center;
      margin: 40px 0;
    }
  }

  .footer-p {
    height: 70px;
  }

  .footer {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 70px;
    padding: 0px 105px;
    box-sizing: border-box;
    z-index: 99;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left {
      display: flex;
      align-items: center;

      .el-checkbox {
        margin-right: 10px;
      }

      p {
        font-size: 14px;
        font-weight: 400;
        color: #ff5757;
        margin-left: 10px;
        cursor: pointer;
        user-select: none;
      }
    }

    .right {
      display: flex;
      align-items: center;

      p {
        font-size: 14px;
        font-weight: 400;
        margin-left: 10px;

        .price {
          font-weight: bold;
          color: #ff0000;
          font-size: 18px;
        }
      }

      .discounts {
        color: #ff0000;
        cursor: pointer;
      }

      .pay {
        margin-left: 20px;
        width: 150px;
        height: 54px;
        background: #ff5757;
        border-radius: 15px;
        font-size: 20px;
        font-weight: 400;
        color: #ffffff;
        border: 0;
      }
    }
  }

  /deep/.el-form-item__content {
    display: flex;

    .el-select {
      margin-right: 10px;
    }

    .el-select:last-child {
      margin-right: 0;
    }
  }

  .dialog-footer {
    button {
      width: 270px;
      height: 55px;
      background: #ff5757;
      border-radius: 10px;
      border: 0;
    }
  }
}

/deep/.el-table {
  tbody {
    tr {
      width: 100%;
      height: 142px;
    }
  }
}

/deep/ .el-table__header {
  width: 100% !important;
}

/deep/ .el-table__body {
  width: 100% !important;
}

/deep/ .elactive {
  background: #f1f1f1 !important;
}
</style>
